package com.llh.controller.http;

import com.llh.bean.FinaIndicator;
import com.llh.bean.StockBasic;
import com.llh.controller.http.common.CommonExcuteTrade;
import com.llh.mapper.FinaIndicatorMapper;
import com.llh.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

public class StockBasicTrade extends CommonExcuteTrade{
    static Logger logger = LogManager.getLogger(StockBasicTrade.class.getName());
    @Override
    public void parseParam(String[][] items, String[] fields) throws Exception {
        //获取sqlSession
        SqlSession sqlSesion = null;
        try {
            //财务数据接口目前只需要一次返回一条数据
            List<FinaIndicator> list = ( List<FinaIndicator>)copyProperty(items, fields);
            sqlSesion = SqlSessionUtil.getSqlSesion();
            FinaIndicatorMapper mapper = sqlSesion.getMapper(FinaIndicatorMapper.class);
            logger.info("插入数据");
            mapper.insert(list.get(0));
            logger.info("插入操作成功");
        }finally {
            sqlSesion.close();;
        }


    }
    public List copyProperty(String[][] items, String[] fields) throws Exception{
        List<StockBasic> stockBasicList = new LinkedList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        for (int j = 0; j < items.length; j++) {
            StockBasic stockBasic = new StockBasic();
            Field[] declaredFields = stockBasic.getClass().getDeclaredFields();
            //参数值数组
            String[] item = items[j];
            //数据值校验
            if(item.length!=fields.length){
                throw new Exception("响应的数据有误");
            }
            for (int i = 0; i < fields.length; i++) {
                //参数名
                String field = fields[i];
                //参数值
                String value = item[i];
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    String fieldName = declaredField.getName();
                    if(field.equals(fieldName)){
                        if(field.equals("list_date")||field.equals("delist_date")){
                            //将字符串转换成date.并赋值
                            if(!(value==null)){
                                declaredField.set(stockBasic,format.parse(value));
                            }
                        }else{
                            //字符串直接赋值
                            declaredField.set(stockBasic,value);
                        }

                    }
                }
            }
            //添加到list集合
            stockBasicList.add(stockBasic);

        }
        return stockBasicList;
    }
}
